package com.lewin.ringroad.net.message;

import io.netty.buffer.ByteBuf;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

/**
 * 虚拟线圈统计数据（0x51）
 *
 * @author Jun
 * @since 1.0.0
 */
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class CoilStatisticsMessage extends BaseMessage {
    //@formatter:off
    /** pos 线位置 */
    private float posLocation;
    /** 检测通道数 */
    private short checkChannelNumber;
    /** 通道统计数据列表 */
    List<ChannelStatisticsData> channelStatisticsDataList;
    /** 报文接收时间 */
    private long receivedTime = System.currentTimeMillis();
    //@formatter:on

    @Override
    public BaseMessage parse(ByteBuf buf) {
        this.posLocation = buf.readFloatLE();
        this.checkChannelNumber = buf.readUnsignedByte();
        this.channelStatisticsDataList = new ArrayList<>(this.checkChannelNumber);
        for (int i = 0; i < this.checkChannelNumber; i++) {
            this.channelStatisticsDataList.add(ChannelStatisticsData.parseFrom(buf));
        }

        return this;
    }

    public boolean isValidData() {
        for (var statisticsData : channelStatisticsDataList) {
            if (statisticsData.isValidData()) {
                return true;
            }
        }
        return false;
    }

    @Data
    public static class ChannelStatisticsData {
        //@formatter:off
        /** 检测通道编号 */
        private short code;
        /** A 类车流量(大型车) */
        private short aTypeTraffic;
        /** B 类车流量（中型车） */
        private short bTypeTraffic;
        /** C 类车流量（小型车） */
        private short cTypeTraffic;
        /** 占有率 */
        private float occupationRate;
        /** 平均车速 */
        private float averageSpeed;
        /** 平均车长 */
        private float averageLength;
        /** 平均车头时距 */
        private float averageHeadTimeInterval;
        //@formatter:on

        public static ChannelStatisticsData parseFrom(ByteBuf buf) {
            ChannelStatisticsData data = new ChannelStatisticsData();
            data.code = buf.readUnsignedByte();
            data.aTypeTraffic = buf.readUnsignedByte();
            data.bTypeTraffic = buf.readUnsignedByte();
            data.cTypeTraffic = buf.readUnsignedByte();
            data.occupationRate = buf.readFloatLE();
            data.averageSpeed = buf.readFloatLE();
            data.averageLength = buf.readFloatLE();
            data.averageHeadTimeInterval = buf.readFloatLE();

            return data;
        }

        /**
         * 判断数据是否有效（存在车辆）
         */
        public boolean isValidData() {
            var a = aTypeTraffic > 0 || bTypeTraffic > 0 || cTypeTraffic > 0;
            return a && averageSpeed >= 0 && averageSpeed <= 180;
        }
    }
}
